package migrate

import (
	"advertising/config/mysql"
	"advertising/internal/define"
	"advertising/internal/models"

	"gorm.io/gorm"
)

// Install 首次安装
// 需要安装数据库和一些默认设置
func Install() error {
	var err error
	db := mysql.NewDB()
	db.Transaction(func(tx *gorm.DB) error {
		// 初始化表结构
		transErr := tx.Set("gorm:table_options", "ENGINE=InnoDB").
			Set("gorm:table_options", "CHARSET=utf8mb4").
			Set("gorm:table_options", "COLLATE=utf8mb4_bin").
			AutoMigrate(models.Models...)
		if transErr != nil {
			err = transErr
			return err
		}
		// 插入数据库版本信息
		{
			var version models.Version
			rs := tx.Model(&models.Version{}).Attrs(models.Version{
				ID:      "1",
				Version: define.DBVersion,
			}).FirstOrCreate(&version)
			if rs.Error != nil {
				return rs.Error
			}
		}
		return nil
	})
	return err
}
